package com.jxc.service.impl;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Hibernate;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.DeliverlistItem;
import com.jxc.model.po.Fhtj;
import com.jxc.model.po.Goods;
import com.jxc.model.po.GoodsRepertory;
import com.jxc.model.po.Fhtj;
import com.jxc.model.po.Repertory;
import com.jxc.model.po.Deliverlist;
import com.jxc.model.po.DeliverlistItem;
import com.jxc.model.po.User;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.VGoodsRepertory;
import com.jxc.model.vo.VDeliverlist;
import com.jxc.service.DeliverlistItemServiceI;
import com.jxc.service.DeliverlistServiceI;
import com.jxc.service.TransferlistServiceI;

@Service("deliverlistService")
public class DeliverlistServiceImpl implements DeliverlistServiceI {

	@Autowired
	private BaseDaoI<Deliverlist> deliverlistDao;
	@Autowired
	private BaseDaoI<DeliverlistItem> deliveritemDao;
	@Autowired
	private BaseDaoI<Goods> goodsDao;
	@Autowired
	private BaseDaoI<GoodsRepertory> goodsreperDao;
	@Override
	public List<VDeliverlist> combobox(VDeliverlist vdl) {
		return this.changeModel(this.find(vdl));
	}

	@Override
	public List<VDeliverlist> search(VDeliverlist vdl) {
		List<Deliverlist> tls = this.find(vdl);
		try {
			for (Deliverlist tl : tls) {
				Hibernate.initialize(tl.getItems());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return this.changeModel(tls);
	}

	@Override
	public DataGrid datagrid(VDeliverlist vtl) {
		vtl.setSort("date");
		vtl.setOrder("desc");
		DataGrid dg = new DataGrid();
		dg.setRows(this.changeModel(this.find(vtl)));
		dg.setTotal(this.total(vtl));
		return dg;
	}

	@Override
	public void delete(String ids) {
		// TODO 是否是物理删除,还要级联删除调拔单明细
		if (ids != null) {
			for (String id : ids.split(",")) {
				if (!id.trim().equals("0")) {
					Deliverlist tl = deliverlistDao.get(Deliverlist.class, Long.parseLong(id.trim()));
					if (tl != null) {
						deliverlistDao.delete(tl);
					}
				}
			}
		}
	}

	/**
	 * 根据传入的Fhtj生成三维柱状图对象
	 * @param list
	 * @return JFreeChart
	 */
	@Override
	public JFreeChart getDeliverChart(List<Fhtj> list) {
		try {
			DefaultCategoryDataset dataset = new DefaultCategoryDataset();
			for(Fhtj fhtj:list){
				System.out.println(fhtj.getFhsum());
				dataset.addValue(fhtj.getFhsum(), fhtj.getDealername(), fhtj.getDealername());
			}
			return  ChartFactory.createBarChart3D("经销商进货统计图",
			  "经销商",
			  "进货量",
			  dataset,
			  PlotOrientation.VERTICAL,
			  true,
			  true,
			  true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public List<Fhtj> findFhsum(Long id){
		List<Fhtj> list = new ArrayList<Fhtj>();
		String hql = "from Fhtj t";//+id;
		list = deliverlistDao.findList(hql);
		return list;
	}
	
	
	@Override
	public Long save(VDeliverlist vdl) {
		Deliverlist dl = new Deliverlist();
		BeanUtils.copyProperties(vdl, dl);
		if (vdl.getUid() != null) {
			dl.setUser(new User(vdl.getUid()));
			dl.setOutConfirmUser(dl.getUser());
		}
		if (vdl.getAgencyId() != null) {
			dl.setAgency(new User(vdl.getAgencyId()));
		}
		if (vdl.getDealerId() != null) {
			dl.setDealer(new User(vdl.getDealerId()));
		}
		if (vdl.getOrid() != null) {
			dl.setOutRepertory(new Repertory(vdl.getOrid()));
		}
		if(vdl.getDate()!=null){
			java.sql.Timestamp time = new java.sql.Timestamp(new java.util.Date().getTime());
			int h = time.getHours();//时
			int f = time.getMinutes();//分
			int m = time.getSeconds();//秒
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			//年月日
			int y = vdl.getDate().getYear()+1900;
			int yf = vdl.getDate().getMonth()+1;
			int day = vdl.getDate().getDate();
			String str = y+"-"+yf+"-"+day+" "+h+":"+f+":"+m;	
			try {
				Date d = sdf.parse(str);
				dl.setDate(d);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		dl.setIsInConfirm(false);
		dl.setIsOutConfirm(true);
		dl.setOutConfirmDate(new Date());
		dl.setConfirmNum(0);
		this.deliverlistDao.save(dl);
		return dl.getId();
	}

	@Override
	public void update(VDeliverlist vdl) {
		Deliverlist tl = deliverlistDao.get(Deliverlist.class, vdl.getId());
		BeanUtils.copyProperties(vdl, tl, new String[] { "id" });
		if (vdl.getUid() != null) {
			tl.setUser(new User(vdl.getUid()));
		}
		if (vdl.getIcuid() != null) {
			tl.setInConfirmUser(new User(vdl.getIcuid()));
		}
		if (vdl.getOcuid() != null) {
			tl.setOutConfirmUser(new User(vdl.getOcuid()));
		}
		if (vdl.getOrid() != null) {
			tl.setOutRepertory(new Repertory(vdl.getOrid()));
		}
	
		this.deliverlistDao.update(tl);
		if(vdl.getIds()!=null&&vdl.getIids()!=null&&vdl.getNums()!=null){
			String gid[] = vdl.getIds().trim().split(",");
			String iid[] = vdl.getIids().trim().split(",");
			String num[] = vdl.getNums().trim().split(",");
			for (int i = 0; i < iid.length; i++) {
				if(!iid[i].equals("*")&&iid[i]!="*"){
				   DeliverlistItem fis = deliveritemDao.get(DeliverlistItem.class, new Long(iid[i]));
				  // Goods g = 
				   fis.setNum(new Integer(num[i]));
				   deliveritemDao.update(fis);
				}else {
					DeliverlistItem fis = new DeliverlistItem();
					Goods goods =  goodsDao.get(Goods.class, new Long(gid[i]));
					fis.setGoods(goods);
					fis.setNum(new Integer(num[i]));
					fis.setDeliverlist(tl);
					deliveritemDao.save(fis);
					
//					vgoodsrepertory vg = new vgoodsrepertory();
//					vg.setgid(new long(gid[i]));
//					vg.set
					String sql = "select t from GoodsRepertory t where t.goods.id="+new Long(gid[i])+" and t.repertory.id="+vdl.getOcuid();
					List<GoodsRepertory> gr = goodsreperDao.find(sql);
					for(GoodsRepertory ff : gr){
						GoodsRepertory cr = goodsreperDao.get(GoodsRepertory.class, ff.getId());
						cr.setNum(cr.getNum()-new Integer(num[i]));
						goodsreperDao.update(cr);
					}
					String sql2 = "select t from GoodsRepertory t where t.goods.id="+new Long(gid[i])+" and t.repertory.id="+vdl.getIcuid();
					List<GoodsRepertory> gr2 = goodsreperDao.find(sql2);
					System.out.println(gr2.size());
					if(gr2.size()==0){
						GoodsRepertory cr = new GoodsRepertory();
						cr.setGoods(goods);
						cr.setRepertory(new Repertory(vdl.getIrid()));
						cr.setNum(new Integer(num[i]));       
						goodsreperDao.save(cr);
					}else {
						for(GoodsRepertory ff : gr2){
							GoodsRepertory cr = goodsreperDao.get(GoodsRepertory.class, ff.getId());
							cr.setNum(cr.getNum()+new Integer(num[i]));
							goodsreperDao.update(cr);
						}
					}
				}
			}
				
			
		}
		
	}

	private List<VDeliverlist> changeModel(List<Deliverlist> tls) {
		List<VDeliverlist> vdls = new ArrayList<VDeliverlist>();
		try {
			if (tls != null && tls.size() > 0) {
				for (Deliverlist tl : tls) {
					VDeliverlist vtl = new VDeliverlist();
					BeanUtils.copyProperties(tl, vtl);

					if (tl.getUser() != null) {
						User user = tl.getUser();
						vtl.setUid(user.getId());
						vtl.setUname(user.getUsername());
					}
					if(tl.getItems()!=null){
						String gid = "";
						String itemsid = "";
						for(DeliverlistItem it:tl.getItems()){
							gid += it.getGoods().getId()+",";		
							itemsid += it.getId()+",";
						}
						vtl.setIds(gid.substring(0,gid.length()-1));
						vtl.setItemsid(itemsid.substring(0,itemsid.length()-1));
					}
					if (tl.getInConfirmUser() != null) {
						User icu = tl.getInConfirmUser();
						vtl.setIcuid(icu.getId());
						vtl.setIcuname(icu.getUsername());
					}
					
					if (tl.getOutConfirmUser() != null) {
						User ocu = tl.getOutConfirmUser();
						vtl.setOcuid(ocu.getId());
						vtl.setOcuname(ocu.getUsername());
					}

					if (tl.getOutRepertory() != null) {
						Repertory or = tl.getOutRepertory();
						vtl.setOrid(or.getId());
						vtl.setOrname(or.getName());
					}

					vdls.add(vtl);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vdls;
	}

	private List<Deliverlist> find(VDeliverlist vtl) {
		String hql = "select t from Deliverlist t join t.items i where 1=1 ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vtl, hql, values);

		if (vtl.getSort() != null && vtl.getOrder() != null) {
			hql += " order by " + vtl.getSort() + " " + vtl.getOrder();
		}
		return deliverlistDao.find(hql, values, vtl.getPage(), vtl.getRows());
	}

	private Long total(VDeliverlist vtl) {
		try {
			String hql = " select count(*) from  (select count(*) from kcgl_deliverlist t inner join kcgl_deliverlist_item i" +
					" on t.id=i.deliverlist_id  where 1=1 ";
			if (vtl.getId() != null) {
				hql += " and t.id = "+vtl.getId();
			}
			if (vtl.getSerial() != null) {
				hql += " and t.serial = "+vtl.getSerial();
			}

			if (vtl.getUid() != null) {
				hql += " and t.user_id = "+vtl.getUid();
			}

			if (vtl.getOcuid() != null) {
				hql += " and t.out_confirm_user_id = "+vtl.getOcuid();
			}

			if (vtl.getIcuid() != null) {
				hql += " and t.in_confirm_user_id = "+vtl.getIcuid();
			}

			if (vtl.getBeginDate() != null) {
				hql += " and t.date >= "+vtl.getBeginDate();
			}

			if (vtl.getEndDate() != null) {
				hql += " and t.date <= "+vtl.getEndDate();
			}

			if (vtl.getIrid() != null) {
				hql += " and t.in_repertory_id = "+vtl.getIrid();
			}
			
			if(vtl.getRid()!=null){
				hql += " and t.in_repertory_id = "+vtl.getRid()+" or  t.out_repertory_id ="+vtl.getRid();
			}

			if (vtl.getOrid() != null) {
				hql += " and t.out_repertory_id = "+vtl.getOrid();
			}
			hql += " group by t.id order by date desc)aa";
			BigInteger a = deliverlistDao.countSQL(hql);
			return a.longValue();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private String addWhere(VDeliverlist vdl, String hql, List<Object> values) {
		if (vdl.getId() != null) {
			hql += " and t.id = ? ";
			values.add(vdl.getId());
		}

		if (vdl.getSerial() != null) {
			hql += " and t.serial = ? ";
			values.add(vdl.getSerial());
		}

		if (vdl.getUid() != null) {
			hql += " and t.user.id = ? ";
			values.add(vdl.getUid());
		}
		
		if (vdl.getDealerId() != null) {
			hql += " and t.dealer.id = ? ";
			values.add(vdl.getDealerId());
		}
		
		if (vdl.getAgencyId() != null) {
			hql += " and t.agency.id = ? ";
			values.add(vdl.getAgencyId());
		}

		if (vdl.getOcuid() != null) {
			hql += " and t.outConfirmUser.id = ? ";
			values.add(vdl.getOcuid());
		}

		if (vdl.getIcuid() != null) {
			hql += " and t.inConfirmUser.id = ? ";
			values.add(vdl.getIcuid());
		}

		if (vdl.getBeginDate() != null) {
			hql += " and t.date >= ? ";
			values.add(vdl.getBeginDate());
		}

		if (vdl.getEndDate() != null) {
			hql += " and t.date <= ? ";
			values.add(vdl.getEndDate());
		}

		if (vdl.getIrid() != null) {
			hql += " and t.inRepertory.id = ? ";
			values.add(vdl.getIrid());
		}
		
		if(vdl.getRid()!=null){
			hql += " and t.inRepertory.id = ? or  t.outRepertory.id = ?";
			values.add(vdl.getRid());
			values.add(vdl.getRid());
		}

		if (vdl.getOrid() != null) {
//			hql += " and ( t.outRepertory.id = ? or ( t.inRepertory.id = ? and t.isOutConfirm = ? ) ) ";
//			values.add(vtl.getOrid());
			hql += " and t.outRepertory.id = ?";
			values.add(vdl.getOrid());
			//values.add(true);
		}
		hql += " group by t.id";
		return hql;
	}

	/* (non-Javadoc)
	 * @see com.jxc.service.DeliverlistServiceI#distributeUpdate(java.lang.String)
	 */
	@Override
	public void distributeUpdate(String dlis) {
		String[] dlisArr  = dlis.split(",");
		Deliverlist dl = new Deliverlist();
		for(int i = 0;i<dlisArr.length;i++){
			DeliverlistItem dli = deliveritemDao.get(DeliverlistItem.class, Long.parseLong(dlisArr[i]));
			dli.setDealerGoods(goodsDao.get(Goods.class, Long.parseLong(dlisArr[++i])));
			dli.setIsConfirm(true);
			deliveritemDao.update(dli);
			dl = dli.getDeliverlist();
		}
		if(dl.getConfirmNum()!=null){
			dl.setConfirmNum(dl.getConfirmNum()+dlisArr.length+1);
		}else{
			dl.setConfirmNum(dlisArr.length+1);
		}
	}

	@Override
	public int findUnconfirmDeliverlist(Long upid) {
		// TODO Auto-generated method stub
		Long ucdlcoount = 1L;
		try{
			String hql = "select count(*) from Deliverlist t where t.confirmNum<t.num and t.dealer.id =" +upid;
			ucdlcoount = (Long) deliverlistDao.findList(hql).get(0);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return ucdlcoount.intValue();
	}

}
